//
// Created by xy on 2024/10/22.
//

#include <pthread.h>
#include <malloc.h>
#include "SafeQueue.h"

// 初始化队列
void queue_init(ThreadSafeCircularQueue* queue, int capacity) {
  queue->capacity = capacity;
  queue->buffer = (void**)malloc(sizeof(void*) * capacity);
  queue->front = 0;
  queue->rear = 0;
  queue->size = 0;
  pthread_mutex_init(&queue->mutex, NULL);
}

// 销毁队列
void queue_destroy(ThreadSafeCircularQueue* queue) {
  free(queue->buffer);
  pthread_mutex_destroy(&queue->mutex);
}

// 入队操作
bool queue_push(ThreadSafeCircularQueue* queue, void* data) {
  pthread_mutex_lock(&queue->mutex);

  // 检查队列是否已满
  if (queue->size == queue->capacity) {
    pthread_mutex_unlock(&queue->mutex);
    return false; // 队列满，无法插入
  }

  queue->buffer[queue->rear] = data;
  queue->rear = (queue->rear + 1) % queue->capacity;
  queue->size++;

  pthread_mutex_unlock(&queue->mutex);
  return true; // 成功插入
}

// 出队操作
void* queue_pop(ThreadSafeCircularQueue* queue) {
  pthread_mutex_lock(&queue->mutex);

  // 检查队列是否为空
  if (queue->size == 0) {
    pthread_mutex_unlock(&queue->mutex);
    return NULL; // 队列空，无法取出
  }

  void* data = queue->buffer[queue->front];
  queue->front = (queue->front + 1) % queue->capacity;
  queue->size--;

  pthread_mutex_unlock(&queue->mutex);
  return data; // 返回出队的数据
}

// 检查队列是否为空
bool queue_is_empty(ThreadSafeCircularQueue* queue) {
  pthread_mutex_lock(&queue->mutex);
  bool empty = (queue->size == 0);
  pthread_mutex_unlock(&queue->mutex);
  return empty;
}

// 检查队列是否已满
bool queue_is_full(ThreadSafeCircularQueue* queue) {
  pthread_mutex_lock(&queue->mutex);
  bool full = (queue->size == queue->capacity);
  pthread_mutex_unlock(&queue->mutex);
  return full;
}

int size(ThreadSafeCircularQueue* queue){
  pthread_mutex_lock(&queue->mutex);
  int size = queue->size ;
  pthread_mutex_unlock(&queue->mutex);
  return size;
}
